﻿using System.IO;
using UnityEngine;

namespace HSFModule
{
    /// <summary>
    /// 此脚本适用于通过Json进行存档操作
    /// </summary>
    public static class SaveJsonSystem
    {
        /// <summary>
        /// 存储Json数据
        /// </summary>
        /// <param name="saveFileName">保存的文件名称</param>
        /// <param name="data">存储的数据</param>
        public static void SaveByJson(string saveFileName, object data)
        {
            var json = JsonUtility.ToJson(data);
            var path = Path.Combine(Application.persistentDataPath, saveFileName);
            try
            {
                File.WriteAllText(path, json);
#if UNITY_EDITOR
                Debug.Log($"Successfully saved data to{path}");
#endif
            }
            catch (System.Exception ex)
            {
                File.WriteAllText(path, json);
#if UNITY_EDITOR
                Debug.Log($"Failed saved data to{path}.\n{ex}");
#endif
            }
        }
        /// <summary>
        /// 读取Json数据
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="saveFileName">保存的文件名称</param>
        /// <returns></returns>
        public static T LoadFromJson<T>(string saveFileName)
        {
            var path = Path.Combine(Application.persistentDataPath, saveFileName);
            try
            {
                var json = File.ReadAllText(path);
                var data = JsonUtility.FromJson<T>(json);
                return data;
            }
            catch (System.Exception exception)
            {
#if UNITY_EDITOR
                Debug.Log($"Failed saved data to{path}.\n{exception}");
#endif
                return default;
            }


        }
        /// <summary>
        /// 删除Json数据
        /// </summary>
        /// <param name="saveFileName">保存的文件名称</param>
        public static void DeleteSaveFile(string saveFileName)
        {
            var path = Path.Combine(Application.persistentDataPath, saveFileName);
            try
            {
                File.Delete(path);
            }
            catch (System.Exception exception)
            {
#if UNITY_EDITOR
                Debug.Log($"Failed delete data to{path}.\n{exception}");
#endif
            }
        }
        /// <summary>
        /// 判断相应存储文件是否存在
        /// </summary>
        /// <param name="saveFileName">保存的文件名称</param>
        /// <returns></returns>
        public static bool SaveFileExists(string saveFileName)
        {
            var path = Path.Combine(Application.persistentDataPath, saveFileName);
            return File.Exists(path);
        }
    }

}
